﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.IO.Compression;
using System.Xml.Serialization;
using System.Drawing;
using System.Drawing.Imaging;

namespace PPClasses
{
    [Serializable]
    public class Problem
    {
        public List<Portal> ThePoints { get; set; }

        [XmlIgnore]
        public Image TheImage { get; set; }

        [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
        [XmlElement("TheImage")]
        public byte[] TheImageSerialized
        {
            get
            {
                // serialize
                if (TheImage == null) return null;
                using (MemoryStream ms = new MemoryStream())
                {
                    using (var gZipStream = new GZipStream(ms, CompressionMode.Compress))
                    {
                        TheImage.Save(gZipStream, ImageFormat.Bmp);
                    }
                    return ms.ToArray();
                }
            }
            set
            {
                // deserialize
                if (value == null)
                {
                    TheImage = null;
                }
                else
                {
                    using (MemoryStream ms = new MemoryStream(value))
                    {
                        using (var gZipStream = new GZipStream(ms, CompressionMode.Decompress))
                        {
                            TheImage = new Bitmap(gZipStream);
                        }
                    }
                }
            }
        }

        public void SaveTo(String filename)
        {
            XmlSerializer serializer = new XmlSerializer(typeof (Problem));
            using (TextWriter textWriter = new StreamWriter(filename))
            {
                serializer.Serialize(textWriter, this);
                textWriter.Close();
            }
        }

        public static Problem LoadFrom(String filename)
        {
            XmlSerializer deserializer = new XmlSerializer(typeof (Problem));
            Problem dd = null;
            using (TextReader textReader = new StreamReader(filename))
            {
                dd = (Problem) deserializer.Deserialize(textReader);
                textReader.Close();
            }
            return dd;
        }
    }
}
